var config = require('../../script/config');
var http = require('../../script/api.js')
import tool from '../../utils/common.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    CommonParam: '',
    userinfo: null,
    pagination: {
      page: 1,
      rows: 10,
      sidx: '',
      sord: ''
    },
    orderList: [],
    canLoadData: true,
    noData: false,
    showPagePop: false,
    AcceptInfo: {
      AuditType: 0,
      ID: '',
      ProcedureCode: '',
      TempResult: '1',
      TempReason: '',
      AuditResult: '1',
      AuditReason: '',
    },
    isSelectLastNode: true,
    showPopup: false,
    TranspondData: {
      ID: '',
      RepairDept: '',
      OrignDept: ''
    },
    // treeList: {},
    UrgencyList: [],
    TimeLimit: [],
    // treeList1: [{
    //   id: '1',
    //   pid: '0',
    //   name: '祖先节点',
    //   nodes: [{
    //       id: '1-1',
    //       pid: '1',
    //       name: '父节点1',
    //       nodes: [{
    //         id: '1-1-1',
    //         pid: '1-1',
    //         name: '子节点1',
    //         nodes: []
    //       }]
    //     },
    //     {
    //       id: '1-2',
    //       pid: '1',
    //       name: '父节点2',
    //       nodes: [{
    //         id: '1-1-2',
    //         pid: '1-1',
    //         name: '子节点2',
    //         nodes: []
    //       }]
    //     }
    //   ]
    // }]
    dataTree: [],
  },
  _refreshData: function () {
    this.setData({ //初始化数据
      pagination: {
        page: 1,
        rows: 10,
        sidx: '',
        sord: ''
      },
      canLoadData: true,
      noData: false,
      showPagePop: false,
      AcceptInfo: {
        ID: '',
        StatusCode: 1,
        UrgencyID: '',
        TimeLimit: '',
        AcceptReason: ''
      },
      showPopup: false,
      TranspondData: {
        ID: '',
        RepairDept: '',
        OrignDept: ''
      },
      // treeList: {},
      // dataTree: [],
      // UrgencyList: [],
      // TimeLimit: [],
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getUserInfo()
    this._refreshData();
    this.GetRepairLogList(true)
    this.GetDeptListTree();
    this.GetUrgency();
    this.GetTimeLimit();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this._refreshData();
    this.GetRepairLogList(true)
    this.GetDeptListTree();
    this.GetUrgency();
    this.GetTimeLimit();
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.canLoadData) {
      this.setData({
        'pagination.page': this.data.pagination.page + 1
      })
      this.GetRepairLogList();
    } else {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 1000
      });
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  call: function (e) {
    var phoneNumber = e.currentTarget.dataset.phone
    var res = wx.getSystemInfoSync();
    if (res.platform == 'ios') {
      wx.makePhoneCall({
        phoneNumber: phoneNumber
      });
    } else {
      wx.showActionSheet({
        itemList: [phoneNumber, '呼叫'],
        success: function (res) {
          if (res.tapIndex == 1) {
            wx.makePhoneCall({
              phoneNumber: phoneNumber
            });
          }
        }
      })
    }
  },
  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo)
      if (value) {
        this.setData({
          userinfo: value
        });
      }
    } catch (e) {
      // Do something when catch error
    }
  },

  inputChange: tool.debounce(function (e) {
    const ev = e[0];
    this.setData({
      CommonParam: ev.detail.value,
    });
    this._refreshData();
    this.GetRepairLogList(true);
  }),
  GetDeptListTree() {
    http.GetDeptListTree({ typeCode: '06,07'}).then(res => {
      if (res.code === 200) {
        this.setData({
          // treeList1: res.data,
          // treeList: res.data[0],
          dataTree: res.data[0].MODELLIST
        })
      }
    })
  },
  GetTimeLimit() {
    http.GetPCode({
      keyValue: 'OrderTimeLimit'
    }).then(res => {
      if (res.code === 200) {
        this.setData({
          TimeLimit: res.data,
          "AcceptInfo.TimeLimit": res.data[0].VALUE,
        })
      }
    })
  },
  GetUrgency() {
    http.GetUrgency().then(res => {
      if (res.code === 200) {
        this.setData({
          UrgencyList: res.data,
          "AcceptInfo.UrgencyID": res.data[0].UrgencyID,
        })
      }
    })
  },
  GetRepairLogList(isRefresh) {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let params = {
      pagination: {
        ...this.data.pagination
      },
      queryParam: {
        StatusCode: 0,
        CommonParam: this.data.CommonParam
      }
    };
    http.GetRepairLogList(params).then(res => {
      if (res.code === 200) {
        let dataList = [];
        for (var i = 0; i < res.data.Items.length; i++) {
          res.data.Items[i].btnStatus = 0;
        }
        if (isRefresh) {
          dataList = [...res.data.Items];
        } else {
          dataList = [...this.data.orderList, ...res.data.Items];
        }
        let canLoadData = res.data.HasNextPages;
        const noData = dataList.length === 0;
        this.setData({
          orderList: dataList,
          canLoadData: canLoadData,
          noData: noData
        });
      }
      wx.hideLoading();
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  hidePopup: function () {
    this.setData({
      showPopup: false,
    });
  },
  treeTap(val) {
    console.log(val);
  },
  toAccept: function (e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showPagePop: true,
      "AcceptInfo.ID": item.ID
      // "AcceptInfo.UrgencyID": item.UrgencyID,
      // "AcceptInfo.TimeLimit": item.TimeLimit,
    });
    if(item.UrgencyID){
      this.setData({
        "AcceptInfo.UrgencyID": item.UrgencyID
      });
    }
    if(item.TimeLimit){
      this.setData({
        "AcceptInfo.TimeLimit": item.TimeLimit
      });
    }
  },
  leave() {
    this.setData({
      "AcceptInfo.ID": '',
      "AcceptInfo.StatusCode": '1',
      "AcceptInfo.UrgencyID": '',
      "AcceptInfo.TimeLimit": '1',
      "AcceptInfo.AcceptReason": '',
      showPagePop: false
    });
  },
  radioStatusCodeChange(e) {
    const val = e.detail.value;
    this.setData({
      "AcceptInfo.StatusCode": val
    });
  },
  radioUrgencyChange(e) {
    const val = e.detail.value;
    this.setData({
      "AcceptInfo.UrgencyID": val
    });
  },
  radioTimeLimitChange(e) {
    const val = e.detail.value;
    this.setData({
      "AcceptInfo.TimeLimit": val
    });
  },
  HandlerReasonChange: function (e) {
    this.setData({
      "AcceptInfo.AcceptReason": e.detail.value
    });
  },
  CloseAccept() {
    this.setData({
      showPagePop: false
    });
  },
  DoAccept() {
    if (this.data.AcceptInfo.StatusCode === '2' &&
      this.data.AcceptInfo.AcceptReason === '') {
      wx.showToast({
        title: '不受理原因不能为空！',
        icon: 'none',
        duration: 2000
      });
      return;
    };
    if(this.data.AcceptInfo.StatusCode === '1'){
        if(this.data.AcceptInfo.UrgencyID == ''){
          wx.showToast({
            title: '请选择紧急程度！',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        if(this.data.AcceptInfo.TimeLimit == ''){
          wx.showToast({
            title: '请选择处理期限！',
            icon: 'none',
            duration: 2000
          });
          return;
        }
    }
    this.setData({
      showPagePop: false
    });
    wx.showLoading({
      title: '数据加载中',
      mask: true
    });
    const params = {
      ID: this.data.AcceptInfo.ID,
      StatusCode: this.data.AcceptInfo.StatusCode,
      UrgencyID: this.data.AcceptInfo.UrgencyID,
      TimeLimit: this.data.AcceptInfo.TimeLimit,
      AcceptReason: this.data.AcceptInfo.AcceptReason
    }
    http.AcceptRepair(params).then(res => {
      if (res.code === 200) {
        const _this = this;
        _this._refreshData();
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              _this.GetRepairLogList(true);
            }, 2000)
          }
        });
      } else {
        wx.showToast({
          icon: 'none',
          title: res.info,
          duration: config.toast.duration
        });
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  showPopup: function (e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showPopup: true,
      "TranspondData.ID": item.ID,
      // "TranspondData.RepairDept": item.RepairStation,
      "TranspondData.OrignDept": item.RepairStation,
    });
  },
  ClosePopup() {
    this.setData({
      showPopup: false,
      "TranspondData.RepairDept": ''
    });
  },
  // treeClick(e) {
  //   console.log(e)
  //   const t = this.selectAllComponents('#treeSelect');
  //   t.forEach(item => {
  //     item.click(e);
  //   })
  //   const {
  //     id,
  //     value
  //   } = e.detail;
  //   this.setData({
  //     'TranspondData.OrignDept': id
  //   });
  //   console.log(e.detail)
  // },
  handleSelect(e) {
    // console.log(e);
    if (e.detail.tips) {
      console.log('必须选择到最后一个节点');
    } else {
      this.setData({
        'TranspondData.RepairDept': e.detail.item.DEPT_NO
      });
    }
  },
  DoTrans() {
    if (this.data.TranspondData.RepairDept === '') {
      wx.showToast({
        title: '请选择转派部门！',
        icon: 'none',
        duration: 2000
      });
      return;
    };
    this.setData({
      showPopup: false
    });
    wx.showLoading({
      title: '数据加载中',
      mask: true
    });
    const params = {
      ID: this.data.TranspondData.ID,
      OrignDept: this.data.TranspondData.OrignDept,
      RepairDept: this.data.TranspondData.RepairDept
    }
    http.TranspondRepair(params).then(res => {
      if (res.code === 200) {
        const _this = this;
        _this._refreshData();
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              _this.GetRepairLogList(true);
            }, 2000)
          }
        });
      } else {
        wx.showToast({
          icon: 'none',
          title: res.info,
          duration: config.toast.duration
        });
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  }
})